package com.cloud.servicezuul.config;

import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulErrorFilter;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPostFilter;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPreFilter;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * 这是初始化sentinel 限流的令牌桶的配置类
 */
@Configuration
public class SentinelConfig {

    //下面这些Bean 是使用 sentinel 封装的 filter
//    @Bean
//    public SentinelZuulPreFilter sentinelZuulPreFilter(){
//        return new SentinelZuulPreFilter();
//    }
//
//    @Bean
//    public SentinelZuulPostFilter sentinelZuulPostFilter(){
//        return new SentinelZuulPostFilter();
//    }
//
//    @Bean
//    public SentinelZuulErrorFilter sentinelZuulErrorFilter(){
//        return new SentinelZuulErrorFilter();
//    }

    /**
     * 开启限流的注解模式
     * @return 注解切面
     */
    @Bean
    public SentinelResourceAspect sentinelResourceAspect(){
        return new SentinelResourceAspect();
    }


    @PostConstruct
    public void init(){
        List<FlowRule> ruleList = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        flowRule.setResource("service-sms");
        flowRule.setCount(2);
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);

        ruleList.add(flowRule);

        FlowRuleManager.loadRules(ruleList);
        System.out.println("Sentinel 令牌桶规则已初始化完毕！");
    }
}
